import random
import re

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from users.models import User
from accounts.serializers import RegisterSmscodeSerializer, SmscodeSerializer, PasswordSerializer
from accounts.utils import get_user_by_account,create_access_token,check_access_token


# 找回密码第一步
class FindPasswordFirstAPIView(APIView):
    def get(self,request,username):
        # 验证用户
        user = get_user_by_account(username)
        if user is not None:
            serializer = RegisterSmscodeSerializer(data=request.query_params)
            serializer.is_valid(raise_exception=True)
            user_mobile = user.mobile
            access_token = create_access_token(user_mobile)
            # mobile = user_mobile.replace(user_mobile[3:7], '****')
            mobile = re.sub(r'(?<=[\d]{3})\d(?=[\d]{4})', '*', user_mobile)
            context = {
                'mobile': mobile,
                'access_token': access_token
            }
            return Response(context)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)




# 找回密码第二步
class FindPasswordSecondAPIView(APIView):
    def get(self, request):

        access_token = request.query_params['access_token']
        mobile = check_access_token(access_token)
        # 发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        # print(sms_code)
        # CCP().send_template_sms(mobile,[sms_code,5],1)

        # 异步发送短信
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        # 保存短信验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # 返回响应
        return Response({'msg':'ok'})


# 找回密码第三步
class FindPasswordThirdAPIView(APIView):
    def get(self,request,username):
        user = get_user_by_account(username)
        mobile = user.mobile
        data = request.query_params.dict()
        serializer = SmscodeSerializer(data=data,context={'mobile':mobile})
        serializer.is_valid(raise_exception=True)
        # user = User.objects.get(username=username)
        user_id = user.id
        access_token = create_access_token(user_id)
        context = {
            'user_id':user_id,
            'access_token':access_token
        }
        return Response(context)


# 找回密码第四步
class FindPasswordFourthAPIView(APIView):
    def post(self,request,user_id):
        data = request.data
        access_token = data['access_token']
        check_user_id = check_access_token(access_token)
        if int(user_id) != check_user_id:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        usr_obj = User.objects.get(id=user_id)
        serializer = PasswordSerializer(instance=usr_obj,data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)
